<template>
  <div class="login-page">
    <img class="login-bg-img" src="@/assets/images/login-bg-1.png" alt="" />
    <lang-switcher :lang="lang" @on-change="setLang" />
    <el-card class="login-card" v-loading="loginLoading">
      <el-form
        ref="submitForm"
        class="login-form"
        :model="formData"
        :rules="formRules"
        label-width="80px"
        label-suffix=": "
      >
        <el-form-item
          class="login-form-item"
          v-for="(value, prop) in formData"
          :key="prop"
          :prop="prop"
          :label="$t(`USER.${strFirstToUpper(prop)}`)"
        >
          <el-input
            class="login-form-component"
            v-model="formData[prop]"
            :placeholder="
              $t('COMMON.PleaseInput', {
                input: $t(`USER.${strFirstToUpper(prop)}`),
              })
            "
            @keydown.native="onKeySubmit"
            :type="prop === 'password' ? 'password' : 'text'"
            :show-password="prop === 'password'"
          />
        </el-form-item>
        <el-form-item>
          <div class="login-form-component">
            <span class="rem-pwd">
              {{ `${$t("USER.RememberPwd")} :` }}
            </span>
            <el-checkbox v-model="isRememberPwd">
              {{ isRememberPwd ? $t("COMMON.Yes") : $t("COMMON.No") }}
            </el-checkbox>
          </div>
        </el-form-item>
        <footer class="submit-area">
          <el-button
            class="op-btn reset"
            type="default"
            @click="onReset"
            size="medium"
          >
            {{ $t("COMMON.Reset") }}
          </el-button>
          <el-button
            class="op-btn login"
            size="medium"
            type="primary"
            @click="onLogin"
          >
            {{ $t("USER.Login") }}
          </el-button>
        </footer>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import LangSwitcher from "@/components/lang-switcher";

import { strFirstToUpper, getLocalStorage } from "@/libs/utils";
import { mapActions } from "vuex";
import {
  SET_USERNAME,
  SET_PASSWORD,
  SET_IS_REMEMBER_PWD,
  SET_USER_INFO,
} from "@/store/user/actionTypes";
import { CUR_USER_INFOS } from "@/configs/keys";
import { lang as langMixin } from "@/mixins";

export default {
  name: "LoginPage",
  components: {
    LangSwitcher,
  },
  mixins: [langMixin],
  data() {
    return {
      formData: {
        username: "",
        password: "",
      },
      /** is-remember-password */
      isRememberPwd: false,
      /** login-loading */
      loginLoading: false,
    };
  },
  computed: {
    submitForm() {
      const { submitForm } = this.$refs;
      return submitForm;
    },
    formRules() {
      const ctx = this;
      return {
        username: {
          required: true,
          message: ctx.$t("COMMON.PleaseInput", {
            input: ctx.$t("USER.Username"),
          }),
          trigger: "blur",
        },
        password: {
          required: true,
          message: ctx.$t("COMMON.PleaseInput", {
            input: ctx.$t("USER.Password"),
          }),
          trigger: "blur",
        },
      };
    },
  },
  mounted() {
    this.initDataFromStore();
  },
  methods: {
    strFirstToUpper,
    ...mapActions("user", [
      SET_USERNAME,
      SET_PASSWORD,
      SET_IS_REMEMBER_PWD,
      SET_USER_INFO,
    ]),

    onReset() {
      if (this.submitForm) {
        this.submitForm.resetFields();
        setTimeout(() => {
          this.submitForm.clearValidate();
        }, 0);
      }
    },
    onKeySubmit(e) {
      const keyCode = e.code.toLowerCase();
      if (keyCode.includes("enter")) {
        this.onLogin();
      }
    },
    onLogin() {
      this.submitForm.validate((valid) => {
        if (!valid) {
          this.$message({
            type: "warning",
            message: this.$t("COMMON.CheckFail"),
            duration: 2000,
          });
          return;
        }
        this.loginLoading = true;
        setTimeout(() => {
          /**
           * 1. 存储到store中 (store关联localStorage)
           */
          this.setInfoToStore();
          this.setLoginInfos();

          this.switchPage();

          this.loginLoading = false;
        }, 800);
      });
    },
    setInfoToStore() {
      const { formData, isRememberPwd } = this,
        { username, password } = formData;

      this[SET_IS_REMEMBER_PWD](isRememberPwd);

      if (isRememberPwd) {
        this[SET_USERNAME](username);
        this[SET_PASSWORD](password);
      }
    },
    setLoginInfos() {
      this[SET_USER_INFO]({
        key: "token",
        value: new Date().getTime(),
      });
    },
    initDataFromStore() {
      const crtUser = getLocalStorage(CUR_USER_INFOS);
      if (!crtUser?.isRememberPwd) {
        localStorage.removeItem(CUR_USER_INFOS);
        return;
      }
      const { isRememberPwd, username, password } = crtUser;
      this.$set(this, "isRememberPwd", isRememberPwd);
      this.$set(this.formData, "username", username);
      this.$set(this.formData, "password", password);
    },
    switchPage() {
      this.$message({
        type: "success",
        message: this.$t("COMMON.OpSuccess", {
          content: this.$t("USER.Login"),
        }),
      });
      this.$router.push("/");
    },
  },
};
</script>

<style lang="scss" scoped>
.login-page {
  position: relative;
  width: 100%;
  height: 100%;

  .login-bg-img {
    display: block;
    width: 100%;
    height: 100vh;
  }

  .login-card {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -75%); // -50%, -50%
    width: 360px;
    box-shadow: 1px 3px 5px #fdfdfd;

    .login-form {
      background-color: #fff;
      padding: 16px 8px 0 0;
      box-sizing: border-box;
      border-radius: 12px;

      .login-form-item {
        .login-form-component {
          // width: 240px;
          color: #353535;
        }
      }

      .op-btn {
        width: 80px;
        height: 36px;
      }
    }
  }

  .submit-area {
    width: 100%;
    text-align: center;
  }
}
</style>
